package com.imooc.portal.job;

import com.imooc.business.processor.DefaultRequestProcessor;
import com.imooc.business.util.DateUtil;
import com.imooc.infra.repository.RuleRepository;
import lombok.Setter;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Component
public class DataProcessJob implements SimpleJob {

    @Setter(onMethod_ = @Autowired)
    private DefaultRequestProcessor defaultRequestProcessor;
    @Setter(onMethod_ = @Autowired)
    private RuleRepository ruleRepository;

    @Override
    public void execute(ShardingContext shardingContext) {
        //当前服务器 可能 1-100
        //3台服务器， 1-》 1-35 业务 2-》 36-75 业务， 3-》 76-100
        List<String> businessIds = null;//ruleRepository.listBusinessIds();
        if (CollectionUtils.isEmpty(businessIds)) {
            return;
        }
        //当前分片下标，当前服务器的下标
        int shardingItem = shardingContext.getShardingItem();
        //总的分片数量，所有服务器的数量
        int shardingTotalCount = shardingContext.getShardingTotalCount();

        //数据的总长度
        int size = businessIds.size();
        Date yesterday = DateUtil.getYesterday();
        for (int i=0; i<size; i++) {
            // i % shardingTotalCount 取值 一定在 [0, shardingTotalCount-1]
            if (i % shardingTotalCount == shardingItem) {
                //表示应该由当前服务器来处理
//                defaultRequestProcessor.process(businessIds.get(i), null, yesterday);
            }
        }
    }
}
